import Vue from 'vue'
class CurrentUser {
  constructor (ticket) {
    this.ticket = ticket
    this.companyAndemployee = {}
    this.roleType = {
      admin: false,
      advancedAdmin: false,
      superAdmin: false,
      projectAdmin: false,
      projectAdvancedAdmin: false
    }
    this.companyInfo = {}
    this.type = 1
    this.roleId = ''
    this.projectRoleType = ''
    this.coId = ''
    this.pjId = ''
  }
  async ssoFinished () {
    await this.ticketVerify()
    await this.findOrganizationInfo()
    await this.canIntoCompany()
    await this.findCompanyInfo()
    await this.domain()
    await this.getUserDepartmentType()
    if (this.type === 2) {
      // 获取项目角色
      await this.findProjectRoleByMid()
    } else {
      // 获取企业角色角色
      await this.findRoleByMid()
    }
    const userInfo = await this.userInfo()
    return userInfo
  }
  // 获取ticket
  ticketVerify () {
    return new Promise(resolve => {
      Vue.prototype.$axios.get(`${Vue.prototype.$site.passportServer}/common/ticketVerify.htm`, {
        params: {
          ticket: this.ticket
        }
      }).then(res => {
        this.isFirstQuery = false
        if (res.data.errorMsg) {
          Vue.prototype.$message.error(res.data.errorMsg)
          setTimeout(() => {
            window.location.replace(`${Vue.prototype.$site.passportServer}`)
          }, 1000)
        } else {
          resolve()
        }
      }, err => {
        const {status} = err.request
        let errText = '请先登入'
        switch (status) {
          case 502:
            errText = '服务器开小差了，请稍候...'
            break
          case 504:
            errText = '服务器开小差了，请稍候...'
            break
        }
        this.isFirstQuery = false
        Vue.prototype.$message.error(errText)
      })
    })
  }
  // 获取用户最后一次用的企业层还是项目层
  findOrganizationInfo () {
    return new Promise((resolve, reject) => {
      Vue.prototype.$axios({
        method: 'get',
        url: `${Vue.prototype.$site.homeServer}/member/findOrganizationInfo.htm`
      }).then(res => {
        if (res.data.errorMsg) {
          reject()
          Vue.prototype.$message.error(res.data.errorMsg)
        } else {
          if (res.data.info) {
            const {info} = res.data
            this.coId = info.coId
            this.pjId = info.pjId
            this.type = info.type
            resolve()
          } else {
            resolve()
          }
        }
      })
    })
  }
  // 获取用户状态
  findCompanyInfo () {
    /**
     * joinStatus 用户状态
     * 1 加入企业
     * 2 申请中
     * 3 未加入企业 也没有申请中的企业
     * null 协作用户 如工人
     * */
    return new Promise((resolve, reject) => {
      Vue.prototype.$axios({
        method: 'post',
        url: `${Vue.prototype.$site.companyServer}/common/findCompanyInfo.htm`
      }).then(res => {
        if (res.data.errorMsg) {
          Vue.prototype.$message.error(res.data.errorMsg)
          reject()
        } else {
          const {company, employee} = res.data
          const joinStatus = company.join_status
          if (joinStatus === 1 || !joinStatus) {
            this.companyAndemployee = {...employee, ...company}
            resolve()
          } else if (joinStatus === 2) {
            reject({joinStatus: 2})
          } else if (joinStatus === 3) {
            reject({joinStatus: 3})
          }
        }
      })
    })
  }
  // 得到当前的项目或者企业
  domain () {
    return new Promise((resolve, reject) => {
      Vue.prototype.$axios({
        method: 'post',
        url: `${Vue.prototype.$site.homeServer}/api/nav/findDomain.htm?type=${this.type}&companyId=${this.companyAndemployee.company_id}`
      }).then(res => {
        if (res.data.errorMsg) {
          Vue.prototype.$message.error(res.data.errorMsg)
          reject()
        } else {
          this.companyInfo = res.data.data
          resolve()
        }
      })
    })
  }
  // 获取管理信息
  findRoleByMid () {
    return new Promise((resolve, reject) => {
      Vue.prototype.$axios({
        method: 'post',
        url: `${Vue.prototype.$site.companyServer}/front/findRoleByMid.htm`
      }).then(res => {
        if (res.data.errorMsg) {
          Vue.prototype.$message.error(res.data.errorMsg)
          reject()
        } else {
          this.roleId = res.data.roleId
          this.setUserRole(res.data.roleId)
          resolve()
        }
      })
    })
  }
  // 是否能进企业端
  canIntoCompany () {
    return new Promise((resolve, reject) => {
      Vue.prototype.$axios({
        method: 'post',
        url: `${Vue.prototype.$site.companyServer}/front/canIntoCompany.htm`
      }).then(res => {
        if (res.data.errorMsg) {
          Vue.prototype.$message.error(res.data.errorMsg)
          reject()
        } else {
          this.type = res.data.success
          resolve()
        }
      })
    })
  }
  getUserDepartmentType () {
    /**
     * 根据部门ID 获取部门类型
     * @param departmentId  部门id
     * @return  部门类型
     */
    return new Promise((resolve, reject) => {
      const data = {
        'query.department_id': this.companyAndemployee.departmentId
      }
      Vue.prototype.$axios({
        method: 'post',
        url: `${Vue.prototype.$site.companyServer}/front/getDeptType.htm`,
        data: Vue.prototype.$qs.stringify(data)
      }).then(res => {
        if (res.data.error) {
          Vue.prototype.$message.error('获取部门类型出错')
          reject()
        } else {
          this.companyAndemployee.departmentType = res.data.type
          resolve()
        }
      })
    })
  }
  // 获取项目管理信息
  findProjectRoleByMid () {
    return new Promise((resolve, reject) => {
      Vue.prototype.$axios({
        method: 'post',
        url: `${Vue.prototype.$site.projectServer}/front/person/findProjectManInfo.htm`
      }).then(res => {
        if (res.data.errorMsg) {
          Vue.prototype.$message.error(res.data.errorMsg)
          reject()
        } else {
          if (res.data.man) {
            this.projectRoleType = res.data.man.type
          }
          resolve()
        }
      })
    })
  }
  // 获取用户信息
  userInfo () {
    return new Promise((resolve, reject) => {
      Vue.prototype.$axios({
        method: 'post',
        url: `${Vue.prototype.$site.passportServer}/member/userInfo.htm`
      }).then(res => {
        const user = res.data.info
        Object.assign(user, {type: this.type})
        Object.assign(user, {coId: this.coId})
        Object.assign(user, {pjId: this.pjId})
        Object.assign(user, {coLogo: this.companyAndemployee.logoUrl})
        Object.assign(user, {code: this.companyAndemployee.code})
        Object.assign(user, {departmentName: this.companyAndemployee.departmentName})
        Object.assign(user, {departmentId: this.companyAndemployee.departmentId})
        Object.assign(user, {belong_dep_code: this.companyAndemployee.belong_dep_code})
        Object.assign(user, {departmentType: this.companyAndemployee.departmentType})
        Object.assign(user, {pjName: this.companyInfo.projectTitle})
        Object.assign(user, {roleId: this.roleId})
        Object.assign(user, {projectRoleType: this.projectRoleType})
        Object.assign(user, {cono: this.companyInfo.cono})
        Object.assign(user, {coName: this.companyInfo.coname})
        Object.assign(user, {admin: this.roleType.admin}) // 部门管理员
        Object.assign(user, {superAdmin: this.roleType.superAdmin}) // 超级管理员
        Object.assign(user, {advancedAdmin: this.roleType.advancedAdmin}) // 企业管理员
        Object.assign(user, {projectAdmin: this.roleType.projectAdmin}) // 项目管理员
        Object.assign(user, {projectAdvancedAdmin: this.roleType.projectAdvancedAdmin}) // 项目负责人
        this.convertUserInfoMLogo(user)
          .then(res => {
            Object.assign(user, {mLogo: res})
          })
          .catch(() => {
            Object.assign(user, {mLogo: ''})
          })
          .finally(() => {
            // Vue.prototype.$store.dispatch({type: 'actSyncContacts'})
            if (user.type === 1) {
              user.manageUrl = Vue.prototype.$site.companyServer
              user.manageText = '企业通行证'
            } else {
              Vue.prototype.$store.dispatch({type: 'actProjectDetail'})
              user.manageUrl = `${Vue.prototype.projectServer}/#/project`
              user.manageText = '项目通行证'
            }
            Vue.prototype.$setCookie('currentUser', JSON.stringify(user), {expires: 14, domain: Vue.prototype.$site.domain})
            resolve(user)
          })
      })
    })
  }
  convertUserInfoMLogo (user) {
    return new Promise((resolve, reject) => {
      const mLogo = user.mLogo
      if (!mLogo) {
        reject()
        return false
      }
      Vue.prototype.$axios({
        method: 'post',
        url: `${Vue.prototype.$site.homeServer}/common/fileDownloadUrl.htm`,
        data: Vue.prototype.$qs.stringify({
          'fileUuid': mLogo,
          'th': 1
        })
      }).then(res => {
        if (res.data.errorMsg) {
          // this.$message.error(res.data.errorMsg)
          reject()
        } else {
          Vue.prototype.$store.commit('editCurrentUser', {mLogo: res.data})
          resolve(res.data)
        }
      })
    })
  }
  setUserProjectRole (roleId) {
    switch (roleId) {
      case 1 : // 项目管理员
        this.roleType.projectAdmin = true
        this.roleType.projectAdvancedAdmin = false
        break
      case 2 : // 项目成员
        this.roleType.projectAdmin = false
        this.roleType.projectAdvancedAdmin = false
        break
      case 4 : // 项目负责人
        this.roleType.projectAdmin = true
        this.roleType.projectAdvancedAdmin = true
        break
    }
  }
  setUserRole (roleId) {
    switch (roleId) {
      case 1 :
        break
      case 2 : // 部门管理员
        this.roleType.admin = true
        this.roleType.advancedAdmin = false
        this.roleType.superAdmin = false
        break
      case 3 : // 超级管理员
        this.roleType.admin = true
        this.roleType.advancedAdmin = true
        this.roleType.superAdmin = true
        break
      case 4 : // 企业管理员
        this.roleType.admin = true
        this.roleType.advancedAdmin = true
        this.roleType.superAdmin = false
        break
    }
  }
}

export default CurrentUser
